<?php
/**
*
* @package acp
* @version $Id: acp_express_categories.php,v 1.012 2008/03/09 15:34:00 nedka Exp $
* @copyright (c) 2008 nedka (Nguyen Dang Khoa)
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

/**
* @package acp
*/
class acp_express_categories
{
	var $u_action;

	function main($id, $mode)
	{
		global $db, $user, $auth, $template, $cache;
		global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx;

		$user->add_lang('mods/express');

		// Set up general vars
		$action = request_var('action', '');
		$action = (isset($_POST['add'])) ? 'add' : $action;
		$action = (isset($_POST['save'])) ? 'save' : $action;
		$cat_id = request_var('id', 0);

		$this->tpl_name = 'acp_express_categories';
		$this->page_title = 'ACP_EXPRESS_CATEGORIES';

		$form_name = 'acp_express_categories';
		add_form_key($form_name);

		switch ($action)
		{
			case 'save':

				if (!check_form_key($form_name))
				{
					trigger_error($user->lang['FORM_INVALID']. adm_back_link($this->u_action), E_USER_WARNING);
				}

				$cat_name = utf8_normalize_nfc(request_var('cat_name', '', true));
				$cat_desc = utf8_normalize_nfc(request_var('cat_desc', '', true));
				$cat_icon = request_var('cat_icon', '');
				$display_on_index = request_var('display_on_index', 1);

				// The category icon has to be a jpg, gif or png
				if ($cat_icon != '' && !preg_match('#(\.gif|\.png|\.jpg|\.jpeg)$#i', $cat_icon))
				{
					$cat_icon = '';
				}

				if (!$cat_name)
				{
					trigger_error($user->lang['NO_CAT_NAME'] . adm_back_link($this->u_action), E_USER_WARNING);
				}

				$sql_ary = array(
					'cat_name'			=> $cat_name,
					'cat_desc'			=> $cat_desc,
					'cat_icon'			=> htmlspecialchars_decode($cat_icon),
					'display_on_index'	=> $display_on_index,
				);

				$order_ary = array(
					'cat_order'	=> $config['num_express_cats'] + 1,
				);

				if ($cat_id)
				{
					$sql = 'UPDATE ' . EXPRESS_CATEGORIES_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . " WHERE cat_id = $cat_id";
					$message = $user->lang['CAT_UPDATED'];

					add_log('admin', 'LOG_EXPRESS_CAT_UPDATED', $cat_name);
				}
				else
				{
					$sql = 'INSERT INTO ' . EXPRESS_CATEGORIES_TABLE . ' ' . $db->sql_build_array('INSERT', array_merge($sql_ary, $order_ary));
					$message = $user->lang['CAT_ADDED'];

					set_config('num_express_cats', $config['num_express_cats'] + 1, true);
					add_log('admin', 'LOG_EXPRESS_CAT_ADDED', $cat_name);
				}
				$db->sql_query($sql);

				trigger_error($message . adm_back_link($this->u_action));

			break;

			case 'delete':

				if (!$cat_id)
				{
					trigger_error($user->lang['MUST_SELECT_CAT'] . adm_back_link($this->u_action), E_USER_WARNING);
				}

				if (confirm_box(true))
				{
					$sql = 'SELECT cat_name, cat_order
						FROM ' . EXPRESS_CATEGORIES_TABLE . "
						WHERE cat_id = $cat_id";
					$result = $db->sql_query($sql);
					$row = $db->sql_fetchrow($result);
					$db->sql_freeresult($result);

					if ($row)
					{
						$row['cat_name'] = (string) $row['cat_name'];
						$row['cat_order'] = (int) $row['cat_order'];
						$row['cat_articles'] = (int) $row['cat_articles'];
					}

					// Delete the selected category
					$sql = 'DELETE FROM ' . EXPRESS_CATEGORIES_TABLE . " WHERE cat_id = $cat_id";
					$db->sql_query($sql);

					// Then, also delete all articles in this category
					$sql = 'DELETE FROM ' . EXPRESS_ARTICLES_TABLE . " WHERE article_cat = $cat_id";
					$db->sql_query($sql);

					// Delete everything else and curse your DB for not offering multi-table deletion
					$tables_ary = array(
						EXPRESS_RATES_TABLE,
						EXPRESS_COMMENTS_TABLE,
					);
	
					$start = 0;

					do
					{
						$sql = 'SELECT article_id
							FROM ' . EXPRESS_ARTICLES_TABLE . "
							WHERE article_cat = $cat_id";
						$result = $db->sql_query_limit($sql, 500, $start);

						$ids = array();
						while ($row = $db->sql_fetchrow($result))
						{
							$ids[] = $row['article_id'];
						}
						$db->sql_freeresult($result);

						if (sizeof($ids))
						{
							$start += sizeof($ids);

							foreach ($tables_ary as $table)
							{
								$db->sql_query("DELETE FROM $table WHERE " . $db->sql_in_set('article_id', $ids));
							}
						}
					}
					while ($row);

					unset($ids);

					// And reset order...
					$sql = 'UPDATE ' . EXPRESS_CATEGORIES_TABLE . ' SET cat_order = cat_order - 1 WHERE cat_order > ' . $row['cat_order'];
					$db->sql_query($sql);

					set_config('num_express_cats', $config['num_express_cats'] - 1, true);
					set_config('num_express_articles', $config['num_express_articles'] - $row['cat_articles'], true);
					add_log('admin', 'LOG_EXPRESS_CAT_REMOVED', $row['cat_name']);
				}
				else
				{
					confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
						'i'			=> $id,
						'mode'		=> $mode,
						'cat_id'	=> $cat_id,
						'action'	=> 'delete',
					)));
				}

			break;

			case 'move_up':
			case 'move_down':

				if (!$cat_id)
				{
					trigger_error($user->lang['MUST_SELECT_CAT'] . adm_back_link($this->u_action), E_USER_WARNING);
				}

				// Get current order id...
				$sql = 'SELECT cat_order AS current_order
					FROM ' . EXPRESS_CATEGORIES_TABLE . "
					WHERE cat_id = $cat_id";
				$result = $db->sql_query($sql);
				$current_order = (int) $db->sql_fetchfield('current_order');
				$db->sql_freeresult($result);

				if ($current_order == 0 && $action == 'move_up')
				{
					break;
				}

				// on move_down, switch position with next order_id...
				// on move_up, switch position with previous order_id...
				$switch_order_id = ($action == 'move_down') ? $current_order + 1 : $current_order - 1;

				// Update order values
				$sql = 'UPDATE ' . EXPRESS_CATEGORIES_TABLE . "
					SET cat_order = $current_order
					WHERE cat_order = $switch_order_id
						AND cat_id <> $cat_id";
				$db->sql_query($sql);

				// Only update the other entry too if the previous entry got updated
				if ($db->sql_affectedrows())
				{
					$sql = 'UPDATE ' . EXPRESS_CATEGORIES_TABLE . "
						SET cat_order = $switch_order_id
						WHERE cat_order = $current_order
							AND cat_id = $cat_id";
					$db->sql_query($sql);
				}

			break;

			case 'resync':

				if (!$cat_id)
				{
					trigger_error($user->lang['MUST_SELECT_CAT'] . adm_back_link($this->u_action), E_USER_WARNING);
				}

				$sql = 'SELECT cat_name
					FROM ' . EXPRESS_CATEGORIES_TABLE . "
					WHERE cat_id = $cat_id";
				$result = $db->sql_query($sql);
				$cat_name = (string) $db->sql_fetchfield('cat_name');
				$db->sql_freeresult($result);

				// Re-count total items of this category
				$sql = 'SELECT COUNT(article_id) as num_articles
					FROM ' . EXPRESS_ARTICLES_TABLE . "
					WHERE article_cat = $cat_id";
				$result = $db->sql_query($sql);
				$total_articles = (int) $db->sql_fetchfield('num_articles');
				$db->sql_freeresult($result);

				$sql = 'UPDATE ' . EXPRESS_CATEGORIES_TABLE . " SET cat_articles = $total_articles WHERE cat_id = $cat_id";
				$db->sql_query($sql);

				add_log('admin', 'LOG_EXPRESS_CAT_RESYNCED', $cat_name);

				$message = sprintf($user->lang['CAT_RESYNCED'], $cat_name);
				trigger_error($message . adm_back_link($this->u_action));

			break;

			case 'edit':
			case 'add':

				$data = $cats = $existing_icons = array();

				$sql = 'SELECT *
					FROM ' . EXPRESS_CATEGORIES_TABLE . '
					ORDER BY cat_order';
				$result = $db->sql_query($sql);

				while ($row = $db->sql_fetchrow($result))
				{
					$existing_icons[] = $row['cat_icon'];

					if ($action == 'edit' && $cat_id == $row['cat_id'])
					{
						$cats = $row;
					}
				}
				$db->sql_freeresult($result);

				$icon_list = filelist($phpbb_root_path . $config['express_icons_path'], '');
				$edit_icon = $icon_filename_list = '';

				foreach ($icon_list as $path => $icon_ary)
				{
					sort($icon_ary);

					foreach ($icon_ary as $icon)
					{
						$icon = $path . $icon;

						if (!in_array($icon, $existing_icons) || $action == 'edit')
						{
							if ($cats && $icon == $cats['cat_icon'])
							{
								$selected = ' selected="selected"';
								$edit_icon = $icon;
							}
							else
							{
								$selected = '';
							}

							if (strlen($icon) > 255)
							{
								continue;
							}

							$icon_filename_list .= '<option value="' . htmlspecialchars($icon) . '"' . $selected . '>' . $icon . '</option>';
						}
					}
				}

				$icon_filename_list = '<option value=""' . (($edit_icon == '') ? ' selected="selected"' : '') . '>' . $user->lang['SELECT_CAT_ICON'] . '</option>' . $icon_filename_list;
				unset($existing_icons, $icon_list);

				$template->assign_vars(array(
					'ICONS_PATH'	=> $phpbb_root_path . $config['express_icons_path'],

					'CAT_NAME'			=> (isset($cats['cat_name'])) ? $cats['cat_name'] : '',
					'CAT_DESC'			=> (isset($cats['cat_desc'])) ? $cats['cat_desc'] : '',
					'CAT_ICON'			=> ($edit_icon) ? $phpbb_root_path . $config['express_icons_path'] . '/' . $edit_icon : $phpbb_admin_path . 'images/spacer.gif',
					'DISPLAY_ON_INDEX'	=> (isset($cats['display_on_index'])) ? $cats['display_on_index'] : true,// Default: Display articles in this category on index

					'U_BACK'	=> $this->u_action,
					'U_ACTION'	=> $this->u_action . '&amp;id=' . $cat_id,

					'S_EDIT'				=> true,
					'S_ICON_FILENAME_LIST'	=> $icon_filename_list,
				));

				return;

			break;
		}

		$template->assign_vars(array(
			'U_ACTION'	=> $this->u_action,
		));

		$sql = 'SELECT *
			FROM ' . EXPRESS_CATEGORIES_TABLE . '
			ORDER BY cat_order';
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$template->assign_block_vars('cats', array(
				'CAT_ICON'			=> $phpbb_root_path . $config['express_icons_path'] . '/' . $row['cat_icon'],
				'CAT_NAME'			=> $row['cat_name'],
				'CAT_DESC'			=> $row['cat_desc'],
				'CAT_ARTICLES'		=> $row['cat_articles'],
				'DISPLAY_ON_INDEX'	=> $row['display_on_index'],

				'U_CAT'			=> append_sid("{$phpbb_admin_path}index.$phpEx", "i=express_articles&amp;mode=articles&amp;cat=" . $row['cat_id']),
				'U_EDIT'		=> $this->u_action . '&amp;action=edit&amp;id=' . $row['cat_id'],
				'U_DELETE'		=> $this->u_action . '&amp;action=delete&amp;id=' . $row['cat_id'],
				'U_RESYNC'		=> $this->u_action . '&amp;action=resync&amp;id=' . $row['cat_id'],
				'U_MOVE_UP'		=> $this->u_action . '&amp;action=move_up&amp;id=' . $row['cat_id'],
				'U_MOVE_DOWN'	=> $this->u_action . '&amp;action=move_down&amp;id=' . $row['cat_id'],

				'S_CAT_ICON'	=> ($row['cat_icon']) ? true : false,
			));	
		}
		$db->sql_freeresult($result);

	}
}

?>